package com.br.aiops.receiver.es.query;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.util.Map;
import java.util.stream.Collectors;

@Builder
@Data
public class ResultFilter {

    private Map<Object, Object> result;

    public ResultFilter filter(Condition condition) {
        Map<Object, Object> filter = result.entrySet().stream().filter(entry -> match(entry.getValue(), condition))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        return ResultFilter.builder().result(filter).build();
    }

    private boolean match(Object value, Condition condition) {
        double localVal = Double.parseDouble(value.toString());

        switch (condition.getOperator()) {
            case Condition.OPERATOR_GT:
                return localVal > condition.getValue();
            case Condition.OPERATOR_GE:
                return localVal >= condition.getValue();
            case Condition.OPERATOR_EQ:
                return localVal == condition.getValue();
            case Condition.OPERATOR_LT:
                return localVal < condition.getValue();
            case Condition.OPERATOR_LE:
                return localVal <= condition.getValue();
            case Condition.OPERATOR_NE:
                return localVal != condition.getValue();
            default:
                throw new IllegalArgumentException("未知condition类型：" + condition);
        }
    }

    @Data
    @AllArgsConstructor
    public static class Condition {
        public static final String OPERATOR_GT = ">";
        public static final String OPERATOR_GE = ">=";
        public static final String OPERATOR_EQ = "==";
        public static final String OPERATOR_LT = "<";
        public static final String OPERATOR_LE = "<=";
        public static final String OPERATOR_NE = "!=";

        private String operator;
        private double value;
    }
}
